package com.hunanwenli.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wanzhenyu
 * @date 2021/6/9 11:12
 */
@Component
@Log4j2
public class SecKillFilter extends ZuulFilter {
    private final RateLimiter rateLimiter = RateLimiter.create(100);
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx =  RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        if(!rateLimiter.tryAcquire()) {
            response.setContentType(MediaType.TEXT_PLAIN_VALUE);
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            response.setCharacterEncoding("UTF-8");
            // 过滤该请求，不对其进行路由
            ctx.setSendZuulResponse(false);
            try {
                response.getWriter().write("当前请求过多，请稍后再试");
            } catch (IOException e) {
                e.printStackTrace();
            }
            ctx.setResponseStatusCode(200);
            log.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:SSS").format(new Date())+"访问ok!!!!!");
        }
    return null;
}}
